<template>
  <n-drawer v-model:show="isDrawer" :width="width" :auto-focus="false" @after-leave="handleReset">
    <n-drawer-content title="代理商管理" closable>
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="120"
      >

        <n-form-item label="登录账号" path="username">
          <n-input
            placeholder="请输入登录账号"
            v-model:value="formParams.username"
            :disabled="formParams.id ? true : false"
          />
        </n-form-item>

        <n-form-item label="名称" path="nickname">
          <n-input placeholder="请输入名称" v-model:value="formParams.nickname" />
        </n-form-item>

        <n-form-item label="密码" :path="!formParams.id ? 'password' : ''">
          <n-input
            type="password"
            show-password-on="mousedown"
            placeholder="请输入密码"
            v-model:value="formParams.password"
          />
        </n-form-item>

        <n-form-item label="确认密码" :path="!formParams.id ? 'passwordRe' : ''">
          <n-input
            type="password"
            show-password-on="mousedown"
            placeholder="请输入密码"
            v-model:value="formParams.passwordRe"
          />
        </n-form-item>

        <n-form-item label="是否参与分成" path="dividedstatus" v-if="dividedStatus">
          <n-radio-group v-model:value="formParams.dividedstatus" @update:value="dividedChange" name="statusGroup">
            <n-space>
              <n-radio :key="1" :value="1">是</n-radio>
              <n-radio :key="0" :value="0">否</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>

        <n-form-item label="充电宝分成比例" path="divided" v-if="divided2">
          <n-input style="width: 200px;" placeholder="请输入分成比例" v-model:value="formParams.divided" /> %
        </n-form-item>

        <n-form-item label="充电线分成比例" path="dividedline" v-if="divided2">
          <n-input style="width: 200px;" placeholder="请输入分成比例" v-model:value="formParams.dividedline" /> %
        </n-form-item>

        <n-form-item label="盒子分成比例" path="dividedbox" v-if="divided2">
          <n-input style="width: 200px;" placeholder="请输入分成比例" v-model:value="formParams.dividedbox" /> %
        </n-form-item>

        <n-form-item label="联系人" path="lxrname">
          <n-input placeholder="请输入联系人" v-model:value="formParams.lxrname" />
        </n-form-item>

        <n-form-item label="手机" path="mobile">
          <n-input placeholder="请输入手机" v-model:value="formParams.mobile" />
        </n-form-item>

        <n-form-item label="所属区域">
          <n-select clearable placeholder="请选择省份" v-model:value="formParams.province" label-field="name" value-field="id" :options="provinceSelect" @update:value="privateChange"/>
          <n-select clearable placeholder="请选择市" v-model:value="formParams.city" label-field="fullname" value-field="id" :options="citySelect" @update:value="cityChange"/>
          <n-select clearable placeholder="请选择区" v-model:value="formParams.district" label-field="fullname" value-field="id" :options="districtSelect"/>
          <n-button type="primary" :loading="subLoading" @click="handleAgent">选择区域</n-button>
        </n-form-item>

        <n-form-item label="详细地址" path="full_address">
          <n-input placeholder="请输入详细地址" v-model:value="formParams.full_address" />
        </n-form-item>

        <n-form-item label="权限">
          <n-space item-style="display: flex;" align="center">
            <n-checkbox v-model:checked="formParams.cities.orderfind" label="订单查看权限" />
            <n-checkbox v-model:checked="formParams.cities.payouts" label="分成比例查看权限" />
            <n-checkbox v-model:checked="formParams.cities.endorder" label="收益记录查看权限" />
            <n-checkbox v-model:checked="formParams.cities.returnorder" label="按日统计" />
          </n-space>
        </n-form-item>

        <n-form-item label="结算方式" path="jsfangshi">
          <n-radio-group v-model:value="formParams.jsfangshi">
            <n-space>
              <n-radio :key="1" :value="1">D+0当天可提现</n-radio>
              <n-radio :key="2" :value="2">D+1第二天可提现</n-radio>
              <n-radio :key="3" :value="3">D+7第七天可提现</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>

        <n-form-item label="合作期限(月)" path="duration">
          <n-input placeholder="请输入合作期限" v-model:value="formParams.duration" @input="qixian" />
        </n-form-item>

        <n-form-item label="结束时间" path="endtime">
          <n-input placeholder="请输入结束时间" v-model:value="formParams.endtime" disabled />
        </n-form-item>

        <n-form-item label="是否启用" path="deleteStatus">
          <n-radio-group v-model:value="formParams.deleteStatus" name="statusGroup">
            <n-space>
              <n-radio :key="1" :value="1">启用</n-radio>
              <n-radio :key="2" :value="2">禁用</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
      </n-form>

      <template #footer>
        <n-space>
          <n-button @click="handleReset">重置</n-button>
          <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
        </n-space>
      </template>

      <n-modal v-model:show="showModal">
        <n-card
          style="width: 900px"
          title="地图选点"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
        <div style="display: flex;align-items: center;">
          <n-input
            placeholder="请输入地址"
            v-model:value="address"
          />
          <div style="width: 30px;margin-left: 5px;">
            <n-button strong secondary circle @click="searchHandle">
              <template #icon>
                <n-icon><Search size="40"/></n-icon>
              </template>
            </n-button>
          </div>
        </div>
        <div id="container" style="width: 800px;height: 400px;margin-top: 10px;">

        </div>
        <div style="display: flex;align-items: center;margin-top: 10px;">
          <div>当前选择地址:</div><div>{{ address }}</div><div> <n-button @click="selectAreaok">确认选择</n-button> </div>
        </div>
        <div>
          <n-table>
            <thead>
              <td>地区</td>
              <td>操作</td>
            </thead>
            <tbody v-for="(item,index) in areaList" :key="index">
              
              <td v-if="item.address==undefined">{{ item.title }}</td>
              <td v-else>{{ item.address }}</td>
              <td>
                <n-button strong secondary @click="selectArea(item)" type="info">
                  确认选择
                </n-button>
              </td>
            </tbody>
          </n-table>
        </div>
        </n-card>
      </n-modal>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { useMessage, FormRules } from 'naive-ui';
  import { useDictionary } from '@/hooks/web/useDictionary';
  import { addUsur, editUsur, userInfo } from '@/api/system/user';
  import { deptTreeList } from '@/api/auth/dept';
  import { postList } from '@/api/auth/post';
  import { getMapList,getProvinceList,getAdcodeSearch,geocoderInfo } from '@/api/device/station';

  const rules: FormRules = {
    username: {
      required: true,
      message: '登录账号不能为空',
      trigger: 'blur',
    }, nickname: {
      required: true,
      message: '名称不能为空',
      trigger: 'blur',
    }, roleIds: {
      required: true,
      message: '角色不能为空',
      trigger: 'change',
      type: 'number',
    }, password: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    }, passwordRe: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    }, mobile: {
      required: true,
      message: '手机号不能为空',
      trigger: 'blur',
    }, lxrname: {
      required: true,
      message: '联系人不能为空',
      trigger: 'blur',
    },full_address: {
      required: true,
      message: '请输入详细地址',
      trigger: 'blur',
    },
  };

  const emit = defineEmits(['change']);
  const { getDictTypeList } = useDictionary();

  const defaultValueRef = () => ({
    id: null,
    roleIds: [11],
    deleteStatus: 1,
    dividedstatus: 1,
    divided: 0,
    dividedline: 0,
    dividedbox: 0,
    email: '',
    lxrname: '',
    mobile: '',
    nickname: '',
    password: '',
    passwordRe: '',
    remark: '',
    sex: 0,
    username: '',
    role_id: 11,
    province: '',
    city: '',
    district: '',
    full_address: '',
    lat: 0,
    lng: 0,
    province_text:'',
    city_text:'',
    district_text:'',
    cities: {
      orderfind: false,
      payouts: false,
      endorder: false,
      returnorder: false
    },
    jsfangshi: 1,
    duration: '',
    endtime: '',
    cooperate: 1,
  });
  const divided2 = ref(true);
  const dividedStatus = ref(true);
  const sexList = ref<any[]>();
  const deptList = ref<any[]>();
  const message = useMessage();
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);
  const postDataList = ref([]);
  const formParams = ref(defaultValueRef());

  defineProps({
    title: {
      type: String,
      default: '添加代理商',
    },
    width: {
      type: Number,
      default: 650,
    },
    roleList: {
      type: Array,
    },
  });

  const showModal = ref(false);
  const provinceSelect = ref([]);
  const citySelect = ref([]);
  const districtSelect = ref([]);
  const address = ref('');
  const areaList = ref([{
    address: '',
    title: '',
  }]);

  const loc = ref({
    lat: 39.98210863924864,//维度
    lng: 116.31310899739151,//经度
    address: '',
    map:'',
  });

  const TMap = (window as any).TMap;
  // const center = new TMap.LatLng(39.98210863924864, 116.31310899739151);
  var markerLayer = null;
  const init =()=>{
    var center = new TMap.LatLng(loc.value.lat, loc.value.lng);//设置中心点坐标
    //初始化地图
    loc.value.map = new TMap.Map("container", {
        center: center,//设置地图中心点坐标
        zoom: 17.2,   //设置地图缩放级别
        pitch: 43.5,  //设置俯仰角
        rotation: 45,    //设置地图旋转角度
    });
    loc.value.map.on('click',clickHandler); // 绑定点击地图获取地理位置的事件
  };

  async function openDrawer(id?) {
    if (id) {
      formParams.value.id = id;
      getInfo();
      return;
    }

    isDrawer.value = true;
  }

  function dividedChange(e){
    if(e==1&&dividedStatus.value){
      divided2.value = true;
    }else{
      divided2.value = false;
    }
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  const reloadMap = () => {
    (document.getElementById('container') as any).innerHTML = '';
    loc.value.map = '';
    var center = new TMap.LatLng(loc.value.lat, loc.value.lng);//设置中心点坐标
    //初始化地图
    loc.value.map = new TMap.Map("container", {
        center: center,//设置地图中心点坐标
        zoom: 17.2,   //设置地图缩放级别
        pitch: 43.5,  //设置俯仰角
        rotation: 45,    //设置地图旋转角度
    });
    loc.value.map.on('click',clickHandler); // 绑定点击地图获取地理位置的事件
  }

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        if (formParams.value.password != formParams.value.passwordRe) {
          return message.error('两次密码不一致');
        }
        const msg = formParams.value.id ? '编辑成功' : '添加成功';      
        formParams.value.roleIds[0] = formParams.value.role_id;
        
        //循环获取一下省份名称
        for(let i=0;i<provinceSelect.value.length;i++){
          if(provinceSelect.value[i].id == formParams.value.province){
            formParams.value.province_text = provinceSelect.value[i].fullname;
          }
        }
        //循环获取一下城市名称
        for(let i=0;i<citySelect.value.length;i++){//循环获取一下
          if(citySelect.value[i].id == formParams.value.city){
            formParams.value.city_text = citySelect.value[i].fullname;
          }
        }
        //循环获取一下区名称
        for(let i=0;i<districtSelect.value.length;i++){//循环获取一下
          if(districtSelect.value[i].id == formParams.value.district){
            formParams.value.district_text = districtSelect.value[i].fullname;
          }
        }

        formParams.value.lat = loc.value.lat;
        formParams.value.lng = loc.value.lng;

        if (formParams.value.id) {
          editUsur(formParams.value).then((_) => {
            message.success(msg);
            emit('change');
            handleReset();
            closeDrawer();
          });
        } else {
          addUsur(formParams.value).then((_) => {
            message.success(msg);
            emit('change');
            handleReset();
            closeDrawer();
          });
        }
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  function handleReset() {
    formRef.value.restoreValidation();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function getInfo() {
    userInfo({ id: formParams.value.id }).then((res) => {
      const params = {
        id: formParams.value.id,
        delete_status: parseInt(res.delete_status),
        email: res.email,
        lxrname: res.lxrname,
        mobile: res.mobile,
        nickname: res.nickname,
        password: '',
        passwordRe: '',
        remark: res.remark,
        sex: res.sex,
        username: res.username,
        roleIds: [11],
        role_id: 11,
        dividedstatus: parseInt(res.dividedstatus),
        divided: res.divided,
        dividedline: res.dividedline,
        dividedbox: res.dividedbox,
        province: res.province,
        city: res.city,
        district: res.district,
        full_address: res.full_address,
        province_text:res.province_text,
        city_text:res.city_text,
        district_text:res.district_text,
        lat: res.lat,
        lng: res.lng,
        jsfangshi: res.jsfangshi,
        cities: res.cities,
        duration: res.duration,
        endtime: res.endtime,
      };
      if(res.dividedstatus==1){
        dividedStatus.value = true;
        divided2.value = true;
      }
      
      loc.value.lat = params.lat;
      loc.value.lng = params.lng;

      formParams.value = Object.assign(formParams.value, params);
      isDrawer.value = true;

      //获取所有的市级列表
      privateChange(res.province);

      //获取所有的区级列表
      cityChange(res.city);

      isDrawer.value = true;
    });
  }

  function qixian(v: string){
    var month = v;
    //查看当前时间月日年
    if(month==''||month==null||month==undefined){
      formParams.value.endtime == '';
    }else{
      let date = new Date();
      date.setMonth(date.getMonth()+parseInt(month));	
      let year = date.getFullYear();//年
      let month1 = date.getMonth() + 1;//月
      let strDate = date.getDate();//日
      if (month1 < 10) month1 = `0${month1}` // 如果月份是个位数，在前面补0
      if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
      formParams.value.endtime = year+"-"+month1+"-"+strDate;
      formParams.value.duration = month;
    }
  }

  function selectAreaok(){
    showModal.value = false;
    formParams.value.full_address = address.value;
  }

  function selectArea(item){
    if(item.address==undefined){
      address.value = item.title;
    }else{
      address.value = item.address;
    }

    formParams.value.full_address = item.address;
    showModal.value = false;

  }

  //移除marker事件
  function removeMarker(){
    if(markerLayer!=null){
      markerLayer.setMap(null);
      markerLayer = null;
    }
  }

  function createMarker(latLng){
    markerLayer = new TMap.MultiMarker({
      id: 'marker',
      map: loc.value.map,
      styles:{
        marker: new TMap.MarkerStyle({
          width: 20, // 样式宽
          height: 30, // 样式高
          anchor: { x: 10, y: 30 }, // 描点位置
        }),
      },
      geometries: [
        // 点标记数据数组
        {
          //标记位置
          position:latLng,
          id: 'marker',
        }
      ]
    });
  }
        
   // 点击获取经纬度
   const clickHandler = (evt:any) => {
    loc.value.lat = evt.latLng.getLat().toFixed(6);//维度
    loc.value.lng = evt.latLng.getLng().toFixed(6);//经度
    removeMarker();
    createMarker(evt.latLng);
    //根据点击坐标获取地址
    geocoderInfo({ 'lat':loc.value.lat,'lng':loc.value.lng }).then((res) => {
      address.value = res.formatted_addresses.standard_address;
      var adcode = res.ad_info.adcode;
      formParams.value.province = adcode.substring(0,2)+'0000';

      //查询一下市列表
      privateChange(formParams.value.province);

      //判断一下是不是直辖市
      if(formParams.value.province=='110000'||formParams.value.province=='120000'||formParams.value.province=='310000'||formParams.value.province=='500000'){
        formParams.value.city = adcode;
        formParams.value.district = adcode;
      }else{

        formParams.value.city = adcode.substring(0,4)+'00';
        // 查询一下区列表
        cityChange(formParams.value.city);
        formParams.value.district = adcode;
      }
    });
  };

  function searchHandle(){
    //搜索
    getMapList({ address:address.value }).then((res) => {
      loc.value.lat = res.data[0].location.lat;;//维度
      loc.value.lng = res.data[0].location.lng;//经度
      if(res.data[0].address==undefined){
        address.value = res.data[0].title;
      }else{
        address.value = res.data[0].address;
      }
      areaList.value = [];
      areaList.value = res.data;
      reloadMap();
      removeMarker();
      createMarker(new TMap.LatLng(loc.value.lat,loc.value.lng));
    })
  }

  function handleAgent(){
    showModal.value = true;
    setTimeout(async () => {
      if(formParams.value.district != ''){
        var result = await getAdcodeSearch({ adcode:formParams.value.district });
        address.value = result.address;
        searchHandle();
      }else{
        init();
      }
    }, 200);
  }

  function addCodeList(){
    getProvinceList({ id: formParams.value.id }).then((res) => {
      provinceSelect.value = res;
    });
  }

  //获取所有的市级列表
  function privateChange(e){
    getProvinceList({ id: formParams.value.id, adcode:e }).then((res) => {
      citySelect.value = res;
      if(e == '110000'||e == '120000'||e == '310000'||e == '500000' ){
        districtSelect.value = citySelect.value;
      }
    });
  }

  //获取所有的区级列表
  function cityChange(e){
    if(formParams.value.province == '110000'||formParams.value.province == '120000'||formParams.value.province == '310000'||formParams.value.province == '500000'){
        districtSelect.value = citySelect.value;
    }else{
      getProvinceList({ id: formParams.value.id, adcode:e }).then((res) => {
        if(res==null){
          districtSelect.value = citySelect.value
        }else{
          districtSelect.value = res;
        }
      });
    }
  }

  onMounted(async () => {
    const list = await getDictTypeList({ dictType: 'sys_user_sex' });
    sexList.value = list;
    const deptResList = await deptTreeList();
    deptList.value = deptResList;
    const postListRes = await postList({ noPage: true });
    postDataList.value = postListRes.list;

    addCodeList();
  });

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
